<?php

namespace app\home\controller\business;


use app\common\controller\Home;

/**
 * 客户订单控制器
 */
class Order extends Home
{
    // 不需要登录的方法
    protected $noNeedLogin = [];

    // 构造函数
    public function __construct()
    {
        parent::__construct();

        $this->OrderModel = model('Subject.Order');
        $this->RecordModel = model('Business.Record');
    }

    // 客户订单列表
    public function index()
    {
        //订单
        //调用模型中定义的关联查询方法的话 需要用到 with 方法
        $orderlist = $this->OrderModel
            ->with(['subject', 'business'])
            ->where(['busid' => $this->LoginAuth['id']])
            ->order('createtime desc')
            ->select();

        //消费记录
        $recordlist = $this->RecordModel->where(['busid' => $this->LoginAuth['id']])->select();

        //赋值
        $this->view->assign([
            'orderlist' => $orderlist,
            'recordlist' => $recordlist,
        ]);

        return $this->view->fetch();
    }

    // 订单评价
    public function comment($orderid = 0)
    {
        // 根据订单id先判断订单是否存在
        $order = $this->OrderModel->with(['subject'])->find($orderid);

        if (!$order) {
            $this->error('订单不存在');
            exit;
        }

        // 请求判断
        if ($this->request->isPost()) {
            $comment = $this->request->param('comment', '', 'trim');
            $rate = $this->request->param('ids', '0', 'trim');

            // 组装数据
            $data = [
                'id' => $order['id'],
                'comment' => $comment,
                'rate' => $rate,
            ];

            // 自定义验证器
            $validate = [
                // 规则
                [
                    'comment' => 'require',
                    'rate' => 'number|in:0,1,2,3,4,5',
                ],
                // 文案
                [
                    'comment.require'  => '评价内容必填',
                    'rate.number'  => '评分内容必须为数字',
                    'rate.in'  => '评分内容必须在0~5之间',
                ]
            ];
            $result = $this->OrderModel->validate(...$validate)->isUpdate(true)->save($data);

            if($result === FALSE)
            {
                $this->error($this->OrderModel->getError());
                exit;
            }else
            {
                $this->success('评价成功');
                exit;
            }
        }

        // 赋值
        $this->view->assign([
            'order' => $order
        ]);

        return $this->view->fetch();
    }
}
